package com.example.framework;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.example.objects.GroupObject;
import com.example.objects.ContactObject;

public class HibernateHelper extends HelperBase {
	
	public HibernateHelper(ApplicationManager manager) {
		super(manager);
	}
	
	@SuppressWarnings("unchecked")
	public Groups getGroups() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction t = session.beginTransaction();
		try {
			return new Groups((List<GroupObject>) session.createQuery(
					"from GroupObject").list());
		} finally {
			t.commit();
		}
	}
	
	@SuppressWarnings("unchecked")
	public Contacts getContacts() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction t = session.beginTransaction();
		try {
			return new Contacts((List<ContactObject>) session.createQuery(
					"from ContactObject").list());
		} finally {
			t.commit();
		}
	}
	
	public String getNextGroupId() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		return session.createSQLQuery("SELECT AUTO_INCREMENT FROM information_schema.TABLES where TABLE_SCHEMA = 'addressbook' and TABLE_NAME = 'group_list'").uniqueResult().toString();
	}
	
	public String getNextContactId() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		return session.createSQLQuery("SELECT AUTO_INCREMENT FROM information_schema.TABLES where TABLE_SCHEMA = 'addressbook' and TABLE_NAME = 'addressbook'").uniqueResult().toString();
//		return session.createQuery("select max(id)from ContactObject").uniqueResult().toString();
	}

}
